<template>
  <div class="login-container">
    <div class="login-wrapper">
      <div class="login-card">
        <!-- 头部 -->
        <div class="login-header">
          <div class="logo">
            <img src="/logo.svg" alt="Logo" />
          </div>
          <h2 class="title">用户登录</h2>
          <p class="subtitle">欢迎回来，请登录您的账户</p>
        </div>

        <!-- 登录表单 -->
        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          size="large"
          label-position="top"
          class="login-form"
        >
          <!-- 用户名 -->
          <el-form-item label="用户名" prop="userName">
            <el-input
              v-model="loginForm.userName"
              placeholder="请输入用户名"
              clearable
              :prefix-icon="User"
              @keyup.enter="handleLogin"
            />
          </el-form-item>

          <!-- 密码 -->
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              show-password
              clearable
              :prefix-icon="Lock"
              @keyup.enter="handleLogin"
            />
          </el-form-item>

          <!-- 记住我和忘记密码 -->
          <div class="form-options">
            <el-checkbox v-model="rememberMe"> 记住我 </el-checkbox>
            <router-link to="/user/forgot-password" class="forgot-link">
              忘记密码？
            </router-link>
          </div>

          <!-- 登录按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              size="large"
              :loading="loginLoading"
              :disabled="loginLoading"
              class="login-btn"
              @click="handleLogin"
            >
              {{ loginLoading ? "登录中..." : "立即登录" }}
            </el-button>
          </el-form-item>

          <!-- 注册链接 -->
          <div class="register-link">
            <span>还没有账户？</span>
            <router-link to="/user/register" class="link">
              立即注册
            </router-link>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { User, Lock } from "@element-plus/icons-vue";
import {
  userLoginApi,
  UserAuthUtils,
  type UserLoginRequest
} from "@/api/user-auth";
import { useUserAuthStore } from "@/store/modules/userAuth";

defineOptions({
  name: "UserLogin"
});

const router = useRouter();
const route = useRoute();
const userAuthStore = useUserAuthStore();

// 表单引用
const loginFormRef = ref<FormInstance>();

// 表单数据
const loginForm = reactive<UserLoginRequest>({
  userName: "cmr2025",
  password: "cmr123456"
});

// 状态管理
const loginLoading = ref(false);
const rememberMe = ref(false);

// 表单验证规则
const loginRules: FormRules = {
  userName: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (!UserAuthUtils.validateUserName(value)) {
          callback(new Error("用户名格式不正确"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (!UserAuthUtils.validatePassword(value)) {
          callback(new Error("密码长度应为6-20字符"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
};

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return;

  try {
    const valid = await loginFormRef.value.validate();
    if (!valid) return;

    loginLoading.value = true;

    const response = await userLoginApi(loginForm);

    if (response.code === 200 && response.data) {
      // 保存用户信息到store
      await userAuthStore.setUserInfo(response.data, rememberMe.value);

      ElMessage.success("登录成功");

      // 触发全局登录事件,让App.vue连接WebSocket
      window.dispatchEvent(
        new CustomEvent("user-login", {
          detail: { token: response.data.token }
        })
      );

      // 获取重定向地址
      const redirect = (route.query.redirect as string) || "/user/home";

      // 跳转到目标页面
      router.push(redirect);
    } else {
      ElMessage.error(response.message || "登录失败");
    }
  } catch (error) {
    ElMessage.error(UserAuthUtils.formatErrorMessage(error));
  } finally {
    loginLoading.value = false;
  }
};
</script>

<style scoped lang="scss">
// 响应式设计
@media (width <= 640px) {
  .login-container {
    padding: 16px;
  }

  .login-card {
    padding: 24px;
  }

  .login-header {
    margin-bottom: 24px;

    .title {
      font-size: 24px;
    }

    .subtitle {
      font-size: 14px;
    }
  }

  .login-form {
    .login-btn {
      height: 44px;
      font-size: 15px;
    }
  }
}

.login-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding: 20px;
  background: #fff;
}

.login-wrapper {
  width: 100%;
  max-width: 400px;
}

.login-card {
  padding: 40px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgb(0 0 0 / 10%);
}

.login-header {
  margin-bottom: 32px;
  text-align: center;

  .logo {
    margin-bottom: 16px;

    img {
      width: 64px;
      height: 64px;
    }
  }

  .title {
    margin: 0 0 8px;
    font-size: 28px;
    font-weight: 600;
    color: #1f2937;
  }

  .subtitle {
    margin: 0;
    font-size: 16px;
    color: #6b7280;
  }
}

.login-form {
  .el-form-item {
    margin-bottom: 20px;

    :deep(.el-form-item__label) {
      margin-bottom: 8px;
      font-weight: 500;
      color: #374151;
    }

    :deep(.el-input__wrapper) {
      border-radius: 8px;
      box-shadow: 0 1px 3px rgb(0 0 0 / 10%);
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 4px 6px rgb(0 0 0 / 10%);
      }

      &.is-focus {
        box-shadow: 0 0 0 2px rgb(64 158 255 / 20%);
      }
    }
  }

  .form-options {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24px;

    .forgot-link {
      font-size: 14px;
      color: #409eff;
      text-decoration: none;

      &:hover {
        color: #337ecc;
        text-decoration: underline;
      }
    }
  }

  .login-btn {
    width: 100%;
    height: 48px;
    font-size: 16px;
    font-weight: 500;
    background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
    border: none;
    border-radius: 8px;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 8px 16px rgb(64 158 255 / 30%);
      transform: translateY(-2px);
    }

    &:active {
      transform: translateY(0);
    }

    &.is-loading,
    &.is-disabled {
      box-shadow: none;
      transform: none;
    }
  }

  .register-link {
    margin-top: 24px;
    color: #6b7280;
    text-align: center;

    .link {
      margin-left: 4px;
      font-weight: 500;
      color: #409eff;
      text-decoration: none;

      &:hover {
        color: #337ecc;
        text-decoration: underline;
      }
    }
  }
}
</style>
